package com.example.administrator.himalaya.criticallies;


import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.himalaya.adapter.MAdapter;
import com.example.administrator.himalaya.R;
import com.example.administrator.himalaya.service.bendiService;
import com.example.administrator.himalaya.entity.castentity.bendiEntity;
import com.example.administrator.himalaya.sqlHelper.Helper;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BeijingFragment extends Fragment implements AbsListView.OnScrollListener, Callback<bendiEntity>, AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    private bendiService mService;
    private int pagerNum = 1;
    private ListView mListView;
    private List<bendiEntity.ResultEntity> datas;
    private MAdapter mAdapter;
    private boolean isButton;
    private int mTotal;
    private SwipeRefreshLayout mRefreshLayout;
    //    判断刷新
    private boolean isRefreshing = false;

    public BeijingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_beijing, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mListView = (ListView) view.findViewById(R.id.listView);
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        mRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.YELLOW, Color.CYAN);
        mRefreshLayout.setOnRefreshListener(this);
        datas = new ArrayList<>();
        mListView.setOnScrollListener(this);
        mService = new Retrofit.Builder()
                .baseUrl("http://live.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(bendiService.class);
        mService.getList(pagerNum, 20, 110000, 2).enqueue(this);
        mAdapter = new MAdapter(getContext(), datas);
        mListView.setAdapter(mAdapter);
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //判断listview第一个可见的条目是否是第一个条目
                if (mListView.getFirstVisiblePosition() == 0) {
                    View firstVisibleItemView = mListView.getChildAt(0);
                    //判断第一个条目距离listview是否是0,如果是，则srLayout可用，否则不可用
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        mRefreshLayout.setEnabled(true);
                    } else {
                        mRefreshLayout.setEnabled(false);
                    }
                } else {
                    mRefreshLayout.setEnabled(false);
                }
                //根据当前是否是在刷新数据，来决定是否拦截listview的触摸事件
                return isRefreshing;
            }
        });
        mListView.setOnItemClickListener(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        if (isButton == true && i == SCROLL_STATE_IDLE) {
            pagerNum++;
            if (pagerNum <= mTotal / 20 + 1) {
                mService = new Retrofit.Builder()
                        .baseUrl("http://live.ximalaya.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(bendiService.class);
                mService.getList(2, 20, 110000, 2).enqueue(this);
            }
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
        if (i + i1 == i2) {
            isButton = true;
        } else {
            isButton = false;
        }
    }

    @Override
    public void onResponse(Call<bendiEntity> call, Response<bendiEntity> response) {
        List<bendiEntity.ResultEntity> result = response.body().getResult();
        Log.d("rname", "onResponse: " + result);
        mTotal = response.body().getTotal();
        datas.addAll(result);
        mAdapter.notifyDataSetChanged();
        mRefreshLayout.setRefreshing(false);
        isRefreshing = false;
    }

    @Override
    public void onFailure(Call<bendiEntity> call, Throwable t) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String title = datas.get(position).getRname();
        String name = datas.get(position).getProgramName();
        int number = datas.get(position).getProgramScheduleId();
        Helper helper = new Helper(getContext());
        SQLiteDatabase db = helper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", title);
        values.put("name", name);
        values.put("number", number);
        db.insert(Helper.TABLE_NAME, null, values);
//        Toast.makeText(this, title +" "+ name +" "+number, Toast.LENGTH_SHORT).show();
        Toast.makeText(getContext(), "添加数据库成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRefresh() {
        datas.clear();
        pagerNum = 1;
        mService = new Retrofit.Builder()
                .baseUrl("http://live.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(bendiService.class);
        mService.getList(pagerNum, 20, 110000, 2).enqueue(this);
        isRefreshing = true;

    }
}